﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EnvDTE;
using Microsoft.VisualStudio.CommandBars;
using System.Xml;
using System.Threading;

using VS4CRM.Lib;

namespace VS4CRM.AddIn.Commands
{
	public class ImportCommand:CommandBase
	{
		 #region constants
        #endregion

        #region fields
        #endregion

        #region public properties
        #endregion

        #region constructor & descructor

		public ImportCommand(DTEHandler dteHandler, ScriptUploader uploader)
            : base(dteHandler, uploader)
        {
        }

        #endregion

        #region public methods


		public static ImportCommand Create(DTEHandler dteHandler, bool beginGroup, CommandBar[] commandbars, ScriptUploader uploader)
        {
			ImportCommand instance = new ImportCommand(dteHandler, uploader);
            instance.CommandInstance = dteHandler.Menu.CreateCommand(
                "IMPORTSELECTED", 
                "&Get from CRM",
				"Gets Selected Items from CRM", 
                "", 
                new ExecuteDelegate(instance.Execute),
                new StatusDelegate(instance.Status));

            dteHandler.Menu.AddToCommandBars(instance.CommandInstance, beginGroup, commandbars);

            return instance;
        }

	
        internal override void Execute()
        {
			EnvDTE.StatusBar statusBar = this.DTEInstance.Application.StatusBar;
			statusBar.Text = "Import from CRM in Progress";

			
				

			try
			{
				SelectedItems selectedItems = this.DTEInstance.AddInInstance.DTE.SelectedItems;
				ProjectItem entityItem = null;
				XmlDocument projectDoc = null;
				_uploader.LoadCustomizations();
				foreach (SelectedItem item in selectedItems)
				{
					try
					{

						string extension = item.ProjectItem.Properties.Item("Extension").Value.ToString();
						if (extension == ".js")
						{
							entityItem = item.ProjectItem.Collection.Parent as ProjectItem;

						}
						else if (extension == ".xml")
						{
							entityItem = item.ProjectItem;
						}


						if (entityItem != null)
						{
							SourceControl sourceControl = DTEInstance.Application.SourceControl;
							if (sourceControl.IsItemUnderSCC(entityItem.get_FileNames(1)))
							{
								if (!sourceControl.IsItemCheckedOut(entityItem.get_FileNames(1)))
								{
									sourceControl.CheckOutItem(entityItem.get_FileNames(1));
									foreach (ProjectItem scriptItem in entityItem.ProjectItems)
									{
										if (!sourceControl.IsItemCheckedOut(scriptItem.get_FileNames(1)))
										{
											sourceControl.CheckOutItem(scriptItem.get_FileNames(1));
										}
									}
								}
							}
							if (projectDoc == null)
							{
								projectDoc = new XmlDocument();
								projectDoc.Load(entityItem.ContainingProject.FileName);
								_uploader.ProjectFile =  (XmlDocument)projectDoc.Clone();
							}

							_uploader.ExportFromCRM(entityItem.get_FileNames(1));
						}
					}
					catch (Exception ex)
					{
						if (entityItem != null)
						{
							string fileName = entityItem.get_FileNames(1);

							this.DTEInstance.ApplicationOutputWindow.ActivePane.OutputTaskItemString(
								"Import Error", vsTaskPriority.vsTaskPriorityHigh, "Imprort Error", vsTaskIcon.vsTaskIconCompile,
								fileName, 0, ex.Message, true);

						}
						throw ex;
					}

				}
				if (projectDoc.InnerXml != _uploader.ProjectFile.InnerXml)
				{
					using (XmlTextWriter tw = new XmlTextWriter(entityItem.ContainingProject.FileName, Encoding.Default))
					{
						_uploader.ProjectFile.WriteTo(tw);
					}
				}

				statusBar.Text = "Import from CRM in Completed.";

			}
			catch (Exception ex)
			{
				this.DTEInstance.ApplicationOutputWindow.ActivePane.OutputString("Import Error: " + ex.Message);
				statusBar.Text = "Import from CRM Failed!";
			}

			
        }

        #endregion

	}
}
